package uf.audit.db;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Model;
import org.apache.log4j.Logger;
import uf.audit.util.Consts;
import uf.audit.util.MD5;
import uf.audit.util.Table;

import java.util.List;
import java.util.UUID;


/**
 * 用户数据实体
 *
 * @author sunny
 */
@Table(key = "userbh")
public class User extends Model<User> {
    private static final Logger log = Logger.getLogger(User.class);
    private static final long serialVersionUID = -7644540082576539659L;
    public static User dao = new User().use(DbKit.MAIN_CONFIG_NAME);

    // 容错处理 如果set的值为空，就不做处理
    public User set(String attr, Object value) {
        if (value != null) {
            super.set(attr, value);
        }
        return this;
    }

    // 校验用户是否可以登录
    public User checkUser(String userName, String password) {
        User rec = null;
        String pwd = MD5.getStringMD5String(password);
        log.info(String.format("username:%s password:%s", userName, pwd));
        rec = findFirst("select * from user where username=? and password=? and enabled=1", userName, pwd);
        return rec;
    }

    // 获取某个机构下面（或者所有）的用户（只获取当前，不包含子机构）
    public List<User> getusers(String orgbh) {
        if (orgbh == null) {
            return find("select * from user");
        } else {
            return find("select * from user where userdep=?", orgbh);
        }
    }

    // 获取某个用户的信息
    public User getuser(String userbh) {
        return findFirst("select * from user where userbh=?", userbh);
    }

    public User getuserByUsername(String username) {
        return User.dao.findFirst("select * from user where username=?", username);
    }

    //select a.*, b.levelname from (select * from user limit 1) a left join worklevel b on a.curlevel=b.levelbh;
    public User getuserByUsernameEx(String username) {
        return User.dao.findFirst("select a.*, b.levelname from (select * from user where username=?) a left join worklevel b on a.curlevel=b.levelbh", username);
    }

    // 获取具有某个权限，某个资源控制权的所有用户
    public List<User> getauthenusers(int type, String resbh) {
        if (resbh == null)
            return find("select * from user where userbh in (select userbh from authentic where authvalue=?)", type);
        else
            return find(
                    "select * from user where userbh in (select userbh from authentic where authvalue=? and resourcebh=?)",
                    type, resbh);
    }

    // 更新
    public boolean update(JSONObject obj) {
        String bh = obj.getString("userbh");
        User item = new User();
        item.set("username", obj.getString("username"));
        item.set("usersex", obj.getString("usersex"));
        item.set("userdep", obj.getString("userdep"));
        item.set("realname", obj.getString("realname"));
        item.set("workseq", obj.getString("workseq"));
        item.set("worktype", obj.getString("worktype"));
        item.set("curlevel", obj.getString("curlevel"));
        item.set("userage", obj.getInteger("userage"));
        item.set("education",obj.getString("education"));
        item.set("schoolname",obj.getString("schoolname"));
        boolean result = false;
        if (bh != null) {
            item.set("userbh", obj.getString("userbh"));
            result = item.update();
        } else {
            item.set("userbh", UUID.randomUUID().toString());
            item.set("password", MD5.getStringMD5String("123456"));
            result = item.save();
        }
        return result;
    }

    // 设置密码
    public boolean setpass(String userbh, String passwd) {
        return DbPro.use().update("update user set password=? where userbh=?", MD5.getStringMD5String(passwd),
                userbh) > 0;
    }

    // 重置密码为123456
    public boolean resetpass(String userbh) {
        return setpass(userbh, Consts.RESET_PASSWORD);
    }

    // 删除
    public boolean delete(String bh) {
        DbPro.use().update("delete from test where userbh=?", bh);
        return deleteById(bh);
    }

    public boolean editStatus(String bh, int status) {
        return User.dao.findById(bh).set("enabled", status).update();
    }
}
